package admin.code.generator.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.log.Logger;
import freemarker.template.Template;

/**
*
* @author dw_chenqi
* @date 2016年3月2日下午4:03:25
*/
public class CodeGenerator {

	private static Logger log = Logger.getLogger(CodeGenerator.class.getName());

	public static void generate(Map root, Template template, String filePath, String fileName) throws Exception {

		log.info("开始生成" + fileName);

		File fDir = new File(filePath);
		if (!fDir.exists()) {
			fDir.mkdirs();
		}
		String realFile = filePath + File.separator + fileName;
		//判断,如果文件存在抛出异常,不进行覆盖
		if (filePath.endsWith(File.separator)) {
			realFile = filePath + fileName;
		}
		File f = new File(realFile);
		if (f.exists()) {
			log.info(realFile + "文件已经存在,退出生成!");
			System.exit(0);
		}
		//Merge data-model with template 
		FileOutputStream fileOutputStream = new FileOutputStream(new File(realFile));
		Writer out = new OutputStreamWriter(fileOutputStream);
		template.process(root, out);
		fileOutputStream.close();

		log.info(fileName + "生成完毕,生成文件所在目录:" + realFile);
	}

}
